﻿using System.Collections.Generic;

namespace Client.Hotfix
{
    public abstract class ObPool<T>
    {
        protected Queue<T> poolQue;
        public int Count => poolQue.Count;
        public ObPool(uint initSize)
        {
            poolQue = new Queue<T>();
            for (int i = 0; i < initSize; i++)
            {
                CreateUnit();
            }
        }


        /// <summary>
        /// 创建池子元素单元
        /// </summary>
        /// <returns></returns>
        protected abstract T CreateUnit();


        /// <summary>
        /// 当池子元素单元放进池子时执行
        /// </summary>
        /// <returns></returns>
        protected abstract void OnPushUnit(T o);

        /// <summary>
        /// 当池子元素单元聪池子拿出时执行
        /// </summary>
        /// <returns></returns>

        protected abstract void OnPopUnit(T o);


        /// <summary>
        /// 放入池子
        /// </summary>
        /// <param name="o"></param>
        public virtual void Push(T o)
        {
            OnPushUnit(o);
            poolQue.Enqueue(o);
        }

        /// <summary>
        /// 从池子中拿出一个
        /// </summary>
        /// <param name="o"></param>
        public virtual T Pop()
        {
            T unit = default(T);
            if (poolQue.Count > 0)
            {
                unit = poolQue.Dequeue();
            }
            else
            {
                unit = CreateUnit();

            }
            OnPopUnit(unit);
            return unit;
        }
    }
}
